<template>
  <view class="register-container">
    <!-- 顶部装饰区域 -->
    <view class="top-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>
    
    <!-- Logo区域 -->
    <view class="logo-section">
      <view class="logo-circle">
        <text class="logo-text">E</text>
      </view>
      <text class="app-name">E-Talk</text>
    </view>
    
    <!-- 步骤一：输入邮箱 -->
    <view v-if="currentStep === 1" class="step-container">
      <!-- 欢迎文字 -->
      <view class="welcome-section">
        <text class="welcome-title">创建账户</text>
        <text class="welcome-subtitle">请输入您的邮箱地址</text>
      </view>
      
      <!-- 邮箱输入表单 -->
      <view class="form-section">
        <view class="input-container">
          <view class="input-wrapper">
            <text class="input-icon">📧</text>
            <input 
              v-model="registerForm.email" 
              placeholder="请输入邮箱地址"
              type="email"
              class="input-field"
            />
          </view>
        </view>
        
        <view class="agreement-section">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-label">
              <checkbox value="agree" :checked="agreed" class="agreement-checkbox" />
              <view class="agreement-content">
                <text class="agreement-text">我已阅读并同意</text>
                <text class="agreement-link" @click="showAgreement">《用户协议》</text>
                <text class="agreement-text">和</text>
                <text class="agreement-link" @click="showPrivacy">《隐私政策》</text>
              </view>
            </label>
          </checkbox-group>
        </view>
        
        <button class="register-button" @click="sendVerificationCode" :disabled="loading || !agreed">
          <text class="button-text">{{ loading ? '发送中...' : '发送验证码' }}</text>
        </button>
      </view>
    </view>
    
    <!-- 步骤二：验证码和密码 -->
    <view v-if="currentStep === 2" class="step-container">
      <!-- 欢迎文字 -->
      <view class="welcome-section">
        <text class="welcome-title">验证邮箱</text>
        <text class="welcome-subtitle">验证码已发送至 {{ registerForm.email }}</text>
      </view>
      
      <!-- 验证表单 -->
      <view class="form-section">
        <view class="input-container">
          <view class="input-wrapper">
            <text class="input-icon">🔢</text>
            <input 
              v-model="registerForm.verificationCode" 
              placeholder="请输入6位验证码"
              type="number"
              maxlength="6"
              class="input-field"
            />
          </view>
        </view>
        
        <view class="input-container">
          <view class="input-wrapper">
            <text class="input-icon">👤</text>
            <input 
              v-model="registerForm.nickName" 
              placeholder="请输入昵称（可选）"
              class="input-field"
            />
          </view>
        </view>
        
        <view class="input-container">
          <view class="input-wrapper">
            <text class="input-icon">🔒</text>
            <input 
              v-model="registerForm.password" 
              type="password"
              placeholder="请输入密码（至少6位）"
              class="input-field"
            />
          </view>
        </view>
        
        <view class="input-container">
          <view class="input-wrapper">
            <text class="input-icon">🔐</text>
            <input 
              v-model="registerForm.confirmPassword" 
              type="password"
              placeholder="请确认密码"
              class="input-field"
            />
          </view>
        </view>
        
        <!-- 重新发送验证码 -->
        <view class="resend-section">
          <text class="resend-text">没有收到验证码？</text>
          <text 
            class="resend-link" 
            @click="resendCode" 
            :class="{ disabled: countdown > 0 }"
          >
            {{ countdown > 0 ? `${countdown}s后重新发送` : '重新发送' }}
          </text>
        </view>
        
        <view class="button-group">
          <button class="back-button" @click="goBack">
            <text class="button-text">返回</text>
          </button>
          <button class="register-button" @click="handleRegister" :disabled="loading">
            <text class="button-text">{{ loading ? '注册中...' : '完成注册' }}</text>
          </button>
        </view>
      </view>
    </view>
    
    <!-- 底部登录链接 -->
    <view class="bottom-section">
      <view class="divider">
        <view class="divider-line"></view>
        <text class="divider-text">或</text>
        <view class="divider-line"></view>
      </view>
      
      <view class="login-section">
        <text class="login-text">已有账户？</text>
        <text class="login-link" @click="goToLogin">立即登录</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { AuthAPI } from '../utils/api'
import { AuthUtils } from '../utils/auth'

// 当前步骤：1-输入邮箱，2-验证码和密码
const currentStep = ref(1)

// 注册表单数据
const registerForm = ref({
  email: '',
  verificationCode: '',
  nickName: '',
  password: '',
  confirmPassword: ''
})

// 状态管理
const loading = ref(false)
const agreed = ref(false)
const countdown = ref(0)
let countdownTimer: any = null

// 协议同意状态变化
const onAgreementChange = (e: any) => {
  agreed.value = e.detail.value.includes('agree')
}

// 验证邮箱格式
const validateEmail = (email: string) => {
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailReg.test(email)
}

// 发送验证码
const sendVerificationCode = async () => {
  const { email } = registerForm.value
  
  if (!email) {
    uni.showToast({
      title: '请输入邮箱地址',
      icon: 'none'
    })
    return
  }
  
  if (!validateEmail(email)) {
    uni.showToast({
      title: '请输入正确的邮箱格式',
      icon: 'none'
    })
    return
  }
  
  if (!agreed.value) {
    uni.showToast({
      title: '请同意用户协议',
      icon: 'none'
    })
    return
  }
  
  loading.value = true
  
  try {
    const response = await AuthAPI.sendVerificationCode(email)
    
    if (response.code === 200) {
      uni.showToast({
        title: '验证码已发送到您的邮箱',
        icon: 'success'
      })
      
      // 进入下一步
      currentStep.value = 2
      
      // 开始倒计时
      startCountdown()
    }
  } catch (error: any) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: error.message || '发送验证码失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
  }, 1000)
}

// 重新发送验证码
const resendCode = async () => {
  if (countdown.value > 0) return
  
  loading.value = true
  
  try {
    const response = await AuthAPI.sendVerificationCode(registerForm.value.email)
    
    if (response.code === 200) {
      uni.showToast({
        title: '验证码已重新发送',
        icon: 'success'
      })
      
      // 重新开始倒计时
      startCountdown()
    }
  } catch (error: any) {
    console.error('重新发送验证码失败:', error)
    uni.showToast({
      title: error.message || '发送验证码失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 返回上一步
const goBack = () => {
  currentStep.value = 1
  // 清除倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
    countdown.value = 0
  }
}

// 验证第二步表单
const validateStep2Form = () => {
  const { verificationCode, password, confirmPassword } = registerForm.value
  
  if (!verificationCode) {
    uni.showToast({
      title: '请输入验证码',
      icon: 'none'
    })
    return false
  }
  
  if (verificationCode.length !== 6) {
    uni.showToast({
      title: '验证码应为6位数字',
      icon: 'none'
    })
    return false
  }
  
  if (!password) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none'
    })
    return false
  }
  
  if (password.length < 6) {
    uni.showToast({
      title: '密码至少6位',
      icon: 'none'
    })
    return false
  }
  
  if (password !== confirmPassword) {
    uni.showToast({
      title: '两次密码不一致',
      icon: 'none'
    })
    return false
  }
  
  return true
}

// 完成注册
const handleRegister = async () => {
  if (!validateStep2Form()) return
  
  loading.value = true
  
  try {
    const { email, verificationCode, nickName, password } = registerForm.value
    
    const response = await AuthAPI.register({
      email,
      verificationCode,
      nickName: nickName || undefined,
      password
    })
    console.log(response)
    
    if (response.code === 200 && response.data) {
      // 保存用户信息和token
      const userInfo =response.data
      AuthUtils.saveUserInfo(userInfo.token, {
      userId: userInfo.userId,
      nickName: userInfo.nickName,
      avatar: userInfo.avatar,
      status: userInfo.status
    })
      uni.showToast({
        title: '注册成功',
        icon: 'success'
      })
      
      // 注册成功后直接登录，跳转到主页面
      setTimeout(() => {
        uni.reLaunch({
          url: '/'
        })
      }, 1000)
    }
  } catch (error: any) {
    console.error('注册失败:', error)
    uni.showToast({
      title: error.message || '注册失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}
// 跳转到登录页面
const goToLogin = () => {
  uni.navigateBack()
}

// 显示用户协议
const showAgreement = () => {
  uni.showToast({
    title: '用户协议页面开发中',
    icon: 'none'
  })
}

// 显示隐私政策
const showPrivacy = () => {
  uni.showToast({
    title: '隐私政策页面开发中',
    icon: 'none'
  })
}

// 页面卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
})
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  padding: 0 50rpx;
  position: relative;
  overflow: hidden;
}

/* 顶部装饰圆圈 */
.top-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 300rpx;
  overflow: hidden;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.circle-1 {
  width: 180rpx;
  height: 180rpx;
  top: -90rpx;
  left: -40rpx;
  animation: float 7s ease-in-out infinite;
}

.circle-2 {
  width: 120rpx;
  height: 120rpx;
  top: 80rpx;
  right: -60rpx;
  animation: float 9s ease-in-out infinite reverse;
}

.circle-3 {
  width: 90rpx;
  height: 90rpx;
  top: 180rpx;
  left: 120rpx;
  animation: float 11s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-15rpx) rotate(180deg); }
}

/* Logo区域 */
.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 120rpx;
  margin-bottom: 50rpx;
}

.logo-circle {
  width: 100rpx;
  height: 100rpx;
  background: rgba(255, 255, 255, 0.25);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
  backdrop-filter: blur(15px);
  border: 2rpx solid rgba(255, 255, 255, 0.4);
}

.logo-text {
  font-size: 42rpx;
  font-weight: bold;
  color: #ffffff;
}

.app-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
  letter-spacing: 2rpx;
}

/* 欢迎区域 */
.welcome-section {
  text-align: center;
  margin-bottom: 60rpx;
}

.welcome-title {
  font-size: 38rpx;
  font-weight: bold;
  color: #ffffff;
  display: block;
  margin-bottom: 12rpx;
}

.welcome-subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  display: block;
}

/* 表单区域 */
.form-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 50rpx 35rpx;
  backdrop-filter: blur(20px);
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.input-container {
  margin-bottom: 28rpx;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 14rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
}

.input-wrapper:focus-within {
  border-color: #764ba2;
  background: #ffffff;
  box-shadow: 0 0 0 6rpx rgba(118, 75, 162, 0.1);
}

.input-icon {
  padding: 0 18rpx;
  font-size: 28rpx;
  color: #999;
}

.input-field {
  flex: 1;
  height: 80rpx;
  padding: 0 18rpx 0 0;
  border: none;
  background: transparent;
  font-size: 26rpx;
  color: #333;
  outline: none;
}

.input-field::placeholder {
  color: #999;
}

/* 协议区域 */
.agreement-section {
  margin-bottom: 35rpx;
}

.agreement-label {
  display: flex;
  align-items: flex-start;
  font-size: 22rpx;
  color: #666;
  line-height: 1.5;
}

.agreement-checkbox {
  margin-right: 12rpx;
  margin-top: 4rpx;
}

.agreement-content {
  flex: 1;
}

.agreement-text {
  color: #666;
}

.agreement-link {
  color: #764ba2;
  text-decoration: underline;
  margin: 0 4rpx;
}

.register-button {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  border: none;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(118, 75, 162, 0.3);
  transition: all 0.3s ease;
}

.register-button:active:not(:disabled) {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(118, 75, 162, 0.3);
}

.register-button:disabled {
  opacity: 0.5;
  transform: none;
  box-shadow: 0 4rpx 12rpx rgba(118, 75, 162, 0.2);
}

.button-text {
  font-size: 30rpx;
  font-weight: 600;
  color: #ffffff;
}

/* 底部区域 */
.bottom-section {
  margin-top: 50rpx;
  padding-bottom: 50rpx;
}

.divider {
  display: flex;
  align-items: center;
  margin-bottom: 35rpx;
}

.divider-line {
  flex: 1;
  height: 1rpx;
  background: rgba(255, 255, 255, 0.3);
}

.divider-text {
  padding: 0 25rpx;
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.7);
}

.login-section {
  text-align: center;
}

.login-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.login-link {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 600;
  margin-left: 8rpx;
  text-decoration: underline;
}

/* 步骤容器 */
.step-container {
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(30rpx);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 重新发送验证码区域 */
.resend-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 35rpx;
  gap: 8rpx;
}

.resend-text {
  font-size: 24rpx;
  color: #666;
}

.resend-link {
  font-size: 24rpx;
  color: #764ba2;
  font-weight: 600;
  text-decoration: underline;
  transition: opacity 0.3s ease;
}

.resend-link.disabled {
  opacity: 0.5;
  text-decoration: none;
}

/* 按钮组 */
.button-group {
  display: flex;
  gap: 20rpx;
}

.back-button {
  flex: 1;
  height: 88rpx;
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.back-button:active {
  transform: translateY(2rpx);
  background: rgba(255, 255, 255, 0.1);
}

.back-button .button-text {
  font-size: 30rpx;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
}

.register-button {
  flex: 2;
}

/* 当在按钮组中时，调整注册按钮样式 */
.button-group .register-button {
  margin: 0;
}

</style>